<?php
require_once 'Zend/Db/Table/Abstract.php';

class MailQueue extends Zend_Db_Table_Abstract {

	protected $_name = "mail_queue";
	protected $_primary = 'id';
	
	/**
	 * Add email to mail queue, mail message is retrieved according to activity type.
	 * 
	 * @param $activityType
	 * @param $subject
	 * @param $recipients
	 * @param $body
	 * @param $created
	 */
	public static function addToQueue($activityType, $subject, $recipients, $body, $created) {
		$mailQueue = new MailQueue();
		$row = $mailQueue->createRow();
		$row->activity_type = $activityType;
		$row->subject = $subject;
		$row->sender = 'no-reply@weimingge.com';
		$row->recipients = $recipients;
		$row->message = $body;
		$row->created = $created;
		$row->sent = false;
		$row->save();
	}
	
	/**
	 * Find all unsent mails from mail queue.
	 * If start date is null, then by default, use current date.
	 * 
	 * @param $startDate start date that criteria search for
	 */
	public static function findUnsentMails($startDate = null) {
		if ($startDate == null) {
			$startDate = date('Y-m-d H:i:s');
		}
		$mailQueue = new MailQueue();
		$select = $mailQueue->select()->where('sent = ?', false)->where('created <= ?', $startDate);
		return $mailQueue->fetchAll($select);
	}
	
	/**
	 * Mark sent mail as sent flag.
	 */
	public static function updateStatus($id) {
		$mailQueue = new MailQueue();
		$m = $mailQueue->find($id)->current();
		$m->sent = true;
		$m->save();
	}
}